package com.lt.net;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;

import com.lt.base.BaseApplication;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.SocketException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NetworkHelper
{

    private static NetworkHelper instance;

    private NetworkHelper()
    {
    }

    public static NetworkHelper getInstance()
    {
        if (instance == null)
        {
            synchronized (NetworkHelper.class)
            {
                instance = new NetworkHelper();
            }
        }
        return instance;
    }

    private static final int NETWORK_TYPE_GSM = 16;
    private static final int NETWORK_TYPE_TD_SCDMA = 17;
    private static final int NETWORK_TYPE_IWLAN = 18;

    public enum NetworkType
    {
        NETWORK_WIFI, NETWORK_4G, NETWORK_3G, NETWORK_2G, NETWORK_UNKNOWN, NETWORK_NO
    }

    /**
     * 获取活动网络信息
     * <p>
     * 需添加权限
     * {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}
     * </p>
     *
     * @return NetworkInfo
     */
    @SuppressLint("MissingPermission")
    private NetworkInfo getActiveNetworkInfo()
    {
        ConnectivityManager cm = (ConnectivityManager) BaseApplication.getContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null)
        {
            try
            {
                return cm.getActiveNetworkInfo();
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 判断网络是否连接
     * <p>
     * 需添加权限
     * {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}
     * </p>
     *
     * @return {@code true}: 是<br>
     * {@code false}: 否
     */
    public boolean isConnected()
    {
        NetworkInfo info = getActiveNetworkInfo();
        return info != null && info.isConnected();
    }


    /**
     * 判断网络是否是4G
     * <p>
     * 需添加权限
     * {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}
     * </p>
     *
     * @return {@code true}: 是<br>
     * {@code false}: 否
     */
    public boolean is4G()
    {
        NetworkInfo info = getActiveNetworkInfo();
        return info != null && info.isAvailable()
                && info.getSubtype() == TelephonyManager.NETWORK_TYPE_LTE;
    }


    /**
     * 判断移动数据是否打开
     *
     * @return {@code true}: 是<br>
     * {@code false}: 否
     */
    @Deprecated
    public boolean getDataEnabled()
    {
        try
        {
            TelephonyManager tm = (TelephonyManager) BaseApplication.getContext()
                    .getSystemService(Context.TELEPHONY_SERVICE);
            Method getMobileDataEnabledMethod = tm.getClass().getDeclaredMethod("getDataEnabled");
            if (null != getMobileDataEnabledMethod)
            {
                return (Boolean) getMobileDataEnabledMethod.invoke(tm);
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 打开或关闭移动数据
     * <p>
     * 需系统应用 需添加权限
     * {@code <uses-permission android:name="android.permission.MODIFY_PHONE_STATE"/>}
     * </p>
     *
     * @param enabled {@code true}: 打开<br>
     *                {@code false}: 关闭
     */
    @Deprecated
    public void setDataEnabled(boolean enabled)
    {
        try
        {
            TelephonyManager tm = (TelephonyManager) BaseApplication.getContext()
                    .getSystemService(Context.TELEPHONY_SERVICE);
            Method setMobileDataEnabledMethod = tm.getClass().getDeclaredMethod("setDataEnabled",
                    boolean.class);
            if (null != setMobileDataEnabledMethod)
            {
                setMobileDataEnabledMethod.invoke(tm, enabled);
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 判断wifi是否打开
     * <p>
     * 需添加权限
     * {@code <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>}
     * </p>
     *
     * @return {@code true}: 是<br>
     * {@code false}: 否
     */
    public boolean getWifiEnabled(Context context)
    {
        WifiManager wifiManager = (WifiManager) context.getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);
        return wifiManager != null && wifiManager.isWifiEnabled();
    }

    /**
     * 打开或关闭wifi
     * <p>
     * 需添加权限
     * {@code <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>}
     * </p>
     *
     * @param enabled {@code true}: 打开<br>
     *                {@code false}: 关闭
     */
    @SuppressLint("MissingPermission")
    public static void setWifiEnabled(Context context, boolean enabled)
    {
        WifiManager wifiManager = (WifiManager) context.getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);
        if (wifiManager != null)
        {
            if (enabled)
            {
                if (!wifiManager.isWifiEnabled())
                {
                    wifiManager.setWifiEnabled(true);
                }
            } else
            {
                if (wifiManager.isWifiEnabled())
                {
                    wifiManager.setWifiEnabled(false);
                }
            }
        }
    }

    /**
     * 判断wifi是否连接状态
     * <p>
     * 需添加权限
     * {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}
     * </p>
     *
     * @return {@code true}: 连接<br>
     * {@code false}: 未连接
     */
    @SuppressLint("MissingPermission")
    public static boolean isWifiConnected(Context context)
    {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null)
        {
            NetworkInfo networkInfo = cm.getActiveNetworkInfo();
            if (networkInfo != null)
            {
                try
                {
                    return networkInfo.isConnected() && networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
                } catch (NullPointerException e)
                {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    /**
     * 获取当前网络类型
     * <p>
     * 需添加权限
     * {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}
     * </p>
     *
     * @return 网络类型
     * <ul>
     * <li>{@link NetworkType#NETWORK_WIFI   }</li>
     * <li>{@link NetworkType#NETWORK_4G     }</li>
     * <li>{@link NetworkType#NETWORK_3G     }</li>
     * <li>{@link NetworkType#NETWORK_2G     }</li>
     * <li>{@link NetworkType#NETWORK_UNKNOWN}</li>
     * <li>{@link NetworkType#NETWORK_NO     }</li>
     * </ul>
     */
    public NetworkType getNetworkType()
    {
        NetworkType netType = NetworkType.NETWORK_NO;
        NetworkInfo info = getActiveNetworkInfo();
        if (info != null && info.isAvailable())
        {

            if (info.getType() == ConnectivityManager.TYPE_WIFI)
            {
                netType = NetworkType.NETWORK_WIFI;
            } else if (info.getType() == ConnectivityManager.TYPE_MOBILE)
            {
                switch (info.getSubtype())
                {

                    case NETWORK_TYPE_GSM:
                    case TelephonyManager.NETWORK_TYPE_GPRS:
                    case TelephonyManager.NETWORK_TYPE_CDMA:
                    case TelephonyManager.NETWORK_TYPE_EDGE:
                    case TelephonyManager.NETWORK_TYPE_1xRTT:
                    case TelephonyManager.NETWORK_TYPE_IDEN:
                        netType = NetworkType.NETWORK_2G;
                        break;

                    case NETWORK_TYPE_TD_SCDMA:
                    case TelephonyManager.NETWORK_TYPE_EVDO_A:
                    case TelephonyManager.NETWORK_TYPE_UMTS:
                    case TelephonyManager.NETWORK_TYPE_EVDO_0:
                    case TelephonyManager.NETWORK_TYPE_HSDPA:
                    case TelephonyManager.NETWORK_TYPE_HSUPA:
                    case TelephonyManager.NETWORK_TYPE_HSPA:
                    case TelephonyManager.NETWORK_TYPE_EVDO_B:
                    case TelephonyManager.NETWORK_TYPE_EHRPD:
                    case TelephonyManager.NETWORK_TYPE_HSPAP:
                        netType = NetworkType.NETWORK_3G;
                        break;

                    case NETWORK_TYPE_IWLAN:
                    case TelephonyManager.NETWORK_TYPE_LTE:
                        netType = NetworkType.NETWORK_4G;
                        break;
                    default:

                        String subtypeName = info.getSubtypeName();
                        if (subtypeName.equalsIgnoreCase("TD-SCDMA")
                                || subtypeName.equalsIgnoreCase("WCDMA")
                                || subtypeName.equalsIgnoreCase("CDMA2000"))
                        {
                            netType = NetworkType.NETWORK_3G;
                        } else
                        {
                            netType = NetworkType.NETWORK_UNKNOWN;
                        }
                        break;
                }
            } else
            {
                netType = NetworkType.NETWORK_UNKNOWN;
            }
        }
        return netType;
    }


    /**
     * @return 返回域名
     */
    public String getDomain(String url)
    {
        try
        {
            URL mURL = new URL(url);
            return mURL.getHost();
        } catch (MalformedURLException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将IP转换成字符串
     */
    public String ipIntToString(int ip)
    {
        try
        {
            byte[] bytes = new byte[4];
            bytes[0] = (byte) (0xFF & ip);
            bytes[1] = (byte) ((0xFF00 & ip) >> 8);
            bytes[2] = (byte) ((0xFF0000 & ip) >> 16);
            bytes[3] = (byte) ((0xFF000000 & ip) >> 24);
            return Inet4Address.getByAddress(bytes).getHostAddress();
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取网络运营商名称
     * <p>
     * 中国移动、如中国联通、中国电信
     * </p>
     *
     * @return 运营商名称
     */
    public String getNetworkOperatorName(Context context)
    {
        TelephonyManager tm = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        return tm != null ? tm.getNetworkOperatorName() : null;
    }

    /**
     * 获取IP地址
     * <p>
     * 需添加权限
     * {@code <uses-permission android:name="android.permission.INTERNET"/>}
     * </p>
     *
     * @param useIPv4 是否用IPv4
     * @return IP地址
     */
    public String getIPAddress(boolean useIPv4)
    {
        try
        {
            for (Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); nis
                    .hasMoreElements(); )
            {
                NetworkInterface ni = nis.nextElement();
                // 防止小米手机返回10.0.2.15
                if (!ni.isUp())
                    continue;
                for (Enumeration<InetAddress> addresses = ni.getInetAddresses(); addresses
                        .hasMoreElements(); )
                {
                    InetAddress inetAddress = addresses.nextElement();
                    if (!inetAddress.isLoopbackAddress())
                    {
                        String hostAddress = inetAddress.getHostAddress();
                        boolean isIPv4 = hostAddress.indexOf(':') < 0;
                        if (useIPv4)
                        {
                            if (isIPv4)
                                return hostAddress;
                        } else
                        {
                            if (!isIPv4)
                            {
                                int index = hostAddress.indexOf('%');
                                return index < 0 ? hostAddress.toUpperCase() : hostAddress
                                        .substring(0, index).toUpperCase();
                            }
                        }
                    }
                }
            }
        } catch (SocketException e)
        {
            e.printStackTrace();
        }
        return null;
    }


    private void ping()
    {
        new Thread(new Runnable()
        {
            @Override
            public void run()
            {

                String lost;
                String delay;
                Process p;
                try
                {
                    p = Runtime.getRuntime().exec("ping -c 4 " + "118.123.244.176");
                    BufferedReader buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
                    String str;
                    while ((str = buf.readLine()) != null)
                    {
                        if (str.contains("packet loss"))
                        {
                            int i = str.indexOf("received");
                            int j = str.indexOf("%");
//                            log("------------------丢包率:" + str.substring(i + 10, j + 1));
                            lost = str.substring(i + 10, j + 1);
                        }
                        if (str.contains("avg"))
                        {
                            int i = str.indexOf("/", 20);
                            int j = str.indexOf(".", i);
//                            log("--------------延迟:" + str.substring(i + 1, j) + "ms");
                            delay = str.substring(i + 1, j);
//                            delay = delay + "ms";
                        }

                    }
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 域名解析成ip
     *
     * @author luotian
     */
    public static class DNSLookupThread extends Thread
    {
        private InetAddress Addr;
        private String hostname;

        public DNSLookupThread(String hostname)
        {
            this.hostname = hostname;
        }

        public void run()
        {
            try
            {
                InetAddress add = InetAddress.getByName(hostname);
                set(add);
            } catch (UnknownHostException e)
            {
                e.printStackTrace();
            }
        }

        private synchronized void set(InetAddress addr)
        {
            this.Addr = addr;
        }

        public synchronized String getIP()
        {
            if (null != this.Addr)
            {
                return Addr.getHostAddress();
            }
            return null;
        }
    }

    public boolean isIP(String addr)
    {
        if (addr.length() < 7 || addr.length() > 15 || "".equals(addr))
        {
            return false;
        }
        /*
         * 判断IP格式和范围
         */
        String rexp = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
        Pattern pat = Pattern.compile(rexp);
        Matcher mat = pat.matcher(addr);
        boolean ipAddress = mat.find();
        //============对之前的ip判断的bug在进行判断
        if (ipAddress)
        {
            String ips[] = addr.split("\\.");
            if (ips.length == 4)
            {
                try
                {
                    for (String ip : ips)
                    {
                        if (Integer.parseInt(ip) < 0 || Integer.parseInt(ip) > 255)
                        {
                            return false;
                        }
                    }
                } catch (Exception e)
                {
                    return false;
                }
                return true;
            } else
            {
                return false;
            }
        }
        return ipAddress;
    }


    public boolean isPortInUse(int port)
    {
        ServerSocket serverSocket = null;
        try
        {
            serverSocket = new ServerSocket(port);
            // 如果能够成功创建ServerSocket，则端口未被占用
            return false;
        } catch (IOException e)
        {
            // 端口已被占用
            return true;
        } finally
        {
            if (serverSocket != null)
            {
                try
                {
                    serverSocket.close();
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
}
